package dao;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import systemServer.reproduction.Song;

public class SongDAO {
	private static SongDAO instance = new SongDAO();
		
	private SongDAO (){
	}
	
	public static SongDAO getInstance (){
		return instance;
	}
 
	public List<Song> getArtistSongs (String artist){
		
		List <Song>listSong = null;
		Transaction tx=Temp.pm.currentTransaction();
	     
	     try{
	    	 tx.begin();
	    	 Query query = Temp.pm.newQuery(Song.class);
	    	 if (!(artist == null || artist.equals("")))
	    	 	query.setFilter("artist == \'"+ artist+"\'");
	    	 listSong = (List<Song>) query.execute();
	    	 tx.commit();
	     }catch (Exception e){
	    	 e.printStackTrace();
	     }finally{
	    	 if (tx.isActive())
	            {
	                tx.rollback();
	            }
	     }
	     return listSong;
	}
	public void addSong (Song song){
		Transaction tx=Temp.pm.currentTransaction();
	     
	     try{
	    	 tx.begin();
	    	 Temp.pm.makePersistent(song);
	    	 tx.commit();
	     }catch (Exception e){
	    	 e.printStackTrace();
	     } finally
	        {
	            if (tx.isActive())
	            {
	                tx.rollback();
	            }
	        }
	}
	
	public Song getSong (int id){
		 Transaction tx=Temp.pm.currentTransaction();
	     Song song = null;
	     try{
	    	 tx.begin();
	    	 Query query = Temp.pm.newQuery(Song.class);
	    	 query.setFilter("id == "+id);
	    	 List <Song>listSong = (List<Song>) query.execute();
	    	 song = listSong.get(0);
	    	 tx.commit();
	     }catch (Exception e){
	    	 e.printStackTrace();
	     }finally{
	    	 if (tx.isActive())
	            {
	                tx.rollback();
	            }
	     }
	     return song;
	}

}
